All Topics

Pointers



A pointer is a variable that stores the memory address as its value.
A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer

First lets see what is a Reference Variable.
A reference variable is a "reference" to an existing variable, and it is created with the & operator


Now, we can use either the variable name 'food' or the reference name 'meal' to refer to the food variable



What is a Memory Address?

In the above example, the & operator was used to create a reference variable. But it can also be used to get the memory address of a variable; which is the location of where the variable is stored on the computer.

When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.
To access it, use the & operator, and the result will represent where the variable is stored

And why is it useful to know the memory address?
References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance.

These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.

Now lets see a code snippet of pointer



Example Explaination:-
Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr).
Note that the type of the pointer has to match the type of the variable you're working with.
Use the & operator to store the memory address of the variable called food, and assign it to the pointer.
Now, ptr holds the value of food's memory address.

You can also use the pointer to get the value of the variable, by using the * operator (the dereference operator)



Hello